package demoutil

import "fmt"
import "strconv"
import "strings"
import "os"
import "net"

// for paxos: persistence on disk
func Port(tag string, host int, DoTcp bool) string {
	// in order to be consitent with most code
	// we continue to have one return argument
	s_ip := ""
	if DoTcp {
		// local network
		//s_ip = "127.0.0.1:" + strconv.Itoa(9000+host)
		// IP
		s_ip = getIP() + ":" + strconv.Itoa(9000+host)
	}
	s := "/var/tmp/824-"
	// hack: we are deleting whole folder of the pid/ during initialization
	// thus it's better to make dir by pid instead of uid
	s += strconv.Itoa(os.Getpid()) + "/"
	os.Mkdir(s, 0777)
	s += "px-"
	s += strconv.Itoa(os.Getuid()) + "-"
	s += tag + "-"
	s += strconv.Itoa(host)
	return s + "?" + s_ip
}
func getIP() string {
	name, err := os.Hostname()
	if err != nil {
		fmt.Printf("ERROR: Hostname: %v\n", err)
		return ""
	}
	addrs, err := net.LookupHost(name)
	if err != nil {
		fmt.Printf("ERROR: Lookup IP: %v\n", err)
		return ""
	}
	/*
		for _, a := range addrs {
			fmt.Println(a)
		}
	*/
	return addrs[0]
}

func ParseAddresses(csv string) []string {
	peers := strings.Split(csv, ",")
	return filter(peers, not_whitespace)
}

func not_whitespace(s string) bool {
	return strings.TrimSpace(s) != ""
}

func filter(a []string, f func(string) bool) []string {
	ret := make([]string, 0)
	for _, s := range a {
		if f(s) {
			ret = append(ret, s)
		}
	}
	return ret
}
		